
var body = "#content-body"
var isShow = true;  //定义一个标志位
var loadingId = '';
// 定义一个变量来记录当前活动的 AJAX 请求数量
var activeRequests = 0;
var templateViewInit;
var iframeCallback;
var tableReturnFilter;
var laydate,inputTag,dropdown,icon,laytpl, element ,table,treeTable,form, layer , util ,upload, $,cron ;
//JS
layui.config({
    base: 'layui/extend/'
}).extend({
    icon: 'icon/iconPick',
    inputTag: 'inputTags/inputTag',
    cron: 'cron/cron',
});
layui.use(['table','treeTable','form', 'element', 'layer', 'util','laytpl','icon','dropdown','inputTag','laydate','cron'], function () {
    laydate = layui.laydate;
    inputTag = layui.inputTag;
    dropdown = layui.dropdown;
    icon = layui.icon;
    laytpl = layui.laytpl;
    form = layui.form;
    element = layui.element;
    table = layui.table;
    treeTable = layui.treeTable;
    layer = layui.layer;
    upload = layui.upload;
    util = layui.util;
    $ = layui.$;
    cron = layui.cron;
    //初始化主题
    let theme = layui.data("layui_theme") ||{};
    top.tools.theme.setTheme(theme.color)
    //初始化菜单
    loadMenu("TPL_menu",document.querySelector(".layui-side-scroll"),function (){
        let lay_href = 'page/index.html';
        let lay_type = '2';
        if (layui.sessionData('lay-href') && layui.sessionData('lay-href').lay_href) {
            lay_href = layui.sessionData('lay-href').lay_href;
            lay_type = '2'
        }
        $('.layui-this').removeClass('layui-this')
        $('.layui-nav-itemed').removeClass('layui-nav-itemed')
        $('#sideMenu a[lay-href="'+lay_href+'"]').parentsUntil('li .layui-nav-item').addClass('layui-nav-itemed')
        $('#sideMenu a[lay-href="'+lay_href+'"]').parent().addClass('layui-this')

        if (lay_type != '2'){
            return
        }
        $('.layui-this').click();
        menuClick(lay_href)
        layui.sessionData('lay-href', {key:'lay_href',value:lay_href});
    })
    // 导航点击事件
    element.on('nav(layadmin-system-side-menu)', function(elem){
        // console.log(elem); // 得到当前点击的元素 jQuery 对象
        //  layer.msg(elem.text());
        let lay_href = $(elem).attr("lay-href");
        let visible = $(elem).attr("visible");
        let tips = $(elem).attr("lay-tips");
        if (lay_href && visible=='self'){
            menuClick(lay_href);
            layui.sessionData('lay-href', {key:'lay_href',value:lay_href});
        }
        if (lay_href && visible=='blank'){
            window.open(lay_href, '_blank');
        }
        if (lay_href && visible=='iframe'){
            const iframe = document.createElement('iframe');
            iframe.src = system_config.basePath+lay_href;
            iframe.width='100%';
            iframe.height='99%';
            // 设置回调方法
            iframe.addEventListener('load', function () {
                console.log('Iframe has finished loading.');
                // 在这里可以执行其他操作，比如获取 iframe 内容
                const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
                if (iframeCallback && typeof iframeCallback === 'function'){
                    iframeCallback(iframeDocument,tips)
                }
                console.log('Iframe document title:', iframeDocument.title);
            });
            $(body).empty();
            document.querySelector(body).appendChild(iframe)
        }
    });

    // 站内消息
    top.tools.message.update(inMessage);
    //头部事件
    util.event('lay-header-event', {
        userinfo:function (init,event){
            let el = init['0'];
            let layhref = $(el).attr('lay-href');
            menuClick(layhref);
            $('.layui-this').removeClass('layui-this')
            $('.layui-nav-itemed').removeClass('layui-nav-itemed')
        },
        resetPassword:function (){
            openForm({
                title:"重置密码",
                btn:1,
                save:(closeid)=>{
                    let formData = top.tools.form.getFindElementOnObj("#lay-reset-password-form",true);
                    formData.id = top.tools.cache.getUser().id;
                    top.API.user().updatePassword(formData,(res)=>{
                        layer.msg(res.message, {icon: 1});
                        if (closeid){
                            layer.close(closeid);
                        }
                    })
                },
                reset:(closeid)=>{
                    form.val('reset-password-form', top.tools.form.getFindElementOnObj("#lay-reset-password-form",false));
                },
                area:'20%',
                before:(closeid)=>{

                }
            },'reset-password-form')
        },
        refresh:function(){
            top.tools.ajax({
                url: "/common/refresh",
                type: "POST",
                successFun: function(response,status,xhr){
                    location.reload(true);
                },
                dataType: "json"
            })
        },
        theme:function(init,event){
            let el = init['0'];
            let title = $(el).data('title');
            let href = $(el).data('href');
            popupRight(title,href,(template)=>{
                laytpl(template).render({}, function(str){
                    document.querySelector('#right_layer').innerHTML = str;
                });
            });
        },
        message:function(init,event){
            let el = init['0'];
            let title = $(el).data('title');
            let href = $(el).data('href');
            popupRight(title,href,(template)=>{
                top.API.msg().getAllRead({},(data)=>{
                    laytpl(template).render(data.data, function(str){
                        document.querySelector('#right_layer').innerHTML = str;
                    });
                })
            });
        },
        logout:function (){
            top.tools.ajax({
                url: '/logout',
                type: 'POST',
                dataType: 'json',
                loading:false,
                data: {},
                successFun:function (res){
                    if (res.code == 200){
                        top.tools.cache.logoutRemove();
                        top.tools.cookie.removeToken();
                        window.location.href = window.location.origin +'/' +system_config.basePath;
                    }
                }
            })
        },
        menuLeft: function (othis) { // 左侧菜单事件
            //判断isshow的状态
            if(isShow){
                $('.layadmin-flexible').html('<i class="layui-icon layui-icon-shrink-right"></i>');
                $('#sideMenu').width(60); //设置宽度
                $('.layui-side-scroll').width(80); //设置宽度
                $('.layui-nav-itemed').each(function () {
                    $(this).removeClass('layui-nav-itemed')
                    $(this).addClass('layui-nav-itemed-item')
                })
                $('.layui-side li cite').hide();
                $('.layui-side li > a>i:first-child').css('font-size','20px');
                //将footer和body的宽度修改
                $('.layui-body').css('left', 60+'px');
                $('.layui-footer').css('left', 60+'px');

                //修改标志位
                isShow =false;
            }else
            {
                $('.layadmin-flexible').html('<i class="layui-icon layui-icon-spread-left"></i>');
                $('#sideMenu').width(200); //设置宽度
                $('.layui-side-scroll').width(220); //设置宽度
                $('.layui-nav-itemed-item').each(function () {
                    $(this).removeClass('layui-nav-itemed-item')
                    $(this).addClass('layui-nav-itemed')
                })
                $('.layui-side li cite').show();
                $('.layui-side li > a>i:first-child').css('font-size','14px');
                $('.layui-body').css('left', 200+'px');
                $('.layui-footer').css('left', 200+'px');

                isShow =true;
            }
        },
        menuRight: function (init,event) {  // 右侧菜单事件
            let el = init['0'];
            let title = $(el).data('title');
            let href = $(el).data('href');
            popupRight(title,href,(template)=>{
                laytpl(template).render({}, function(str){
                    document.querySelector('#right_layer').innerHTML = str;
                });
            });
        }
    });
    util.event('lay-theme-event', {
        setTheme:function(init,event){
            let el = init['0'];
            let a = $(el).data('index');
            $(el).siblings(".layui-this").data("index");
            if(!$(el).hasClass('layui-this')){
                $(el).addClass('layui-this').siblings(".layui-this").removeClass('layui-this');
                top.tools.theme.initTheme(a)
            }
        },
    });
    util.event('lay-message-event', {
        message:function (init,event) {
            let el = init['0'];
            let id = $(el).data('msgid');
            top.API.msg().getMsgById(id,(data)=>{
                /*laytpl(template).render(data, function(str){
                    document.querySelector('#right_layer').innerHTML = str;
                });*/
            })
        }
    })

    // 自定义验证规则
    form.verify({
        pass: function(value) {
            var regex = new RegExp('^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,30}$');
            if(!regex.test(value)){
                return "密码不符合规则，请重新输入。";
            }
        },
        verifyPass:function (value, elem) {
            let password = $('input[type=text][name=password],[type=password][name=password]').val()
            if (value !== password){
                return "密码不正确，请重新输入。";
            }
        },
        domain:function (value, elem){
            let regex = new RegExp('^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$');
            if(!regex.test(value)){
                return "域名不符合规则，请重新输入。";
            }
        }
    });
    // 加载菜单
    function loadMenu(templateID,elemView,callback) {
        /*let getTpl = document.getElementById(templateID).innerHTML; // 获取模板字符
        let data = {}
        top.tools.ajax({
            url: $('#'+templateID).attr("lay-url"),
            async: false,
            successFun: function(response,status,xhr){
                data = response
            },
            dataType: "json"
        });

        laytpl(getTpl).render(data.data, function(str){
            elemView.innerHTML = str;
        });*/
        element.init();
        if (callback && typeof callback == "function"){
            callback();
        }
    }
    //菜单点击
    function menuClick(url){
        top.API.common().loadPage(url,function (response){
            $(body).empty();
            laytpl(response).render({}, function(str){
                document.querySelector(body).innerHTML = str;
            });
        })
    }

});
iframeCallback= function(document,type){
    type = type.toLowerCase();
    if (type.includes("mysql")){
        // 通过 name 属性找到 input 元素
        const loginUsername = document.querySelector('input[name="loginUsername"]');
        const loginPassword = document.querySelector('input[name="loginPassword"]');
        if (loginUsername) {
            // 设置 input 元素的值
            loginUsername.value = 'admin';
        }
        if (loginPassword) {
            // 设置 input 元素的值
            loginPassword.value = 'admin';
        }

        // 找到按钮元素，这里假设按钮的 id 是 loginButton
        const buttonElement = document.getElementById('loginBtn');
        if (buttonElement) {
            // 触发按钮的点击事件
            buttonElement.click();
        }
    }
}

//更多菜单
function dropdownMenu(elem,menu,align,style){
    // 更多下拉菜单
    dropdown.render({
        elem: elem,
        show: true, // 外部事件触发即显示
        data: menu,
        click: function(data, othis){
            data.fun();
        },
        align: align || 'right', // 右对齐弹出
        style: style || 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
    })
}
//右侧弹窗
function popupRight(title,href,callback){
    layer.open({
        type: 1,
        title: title,
        content: '<div id="right_layer">处理右侧面板的操作</div>',
        area: ['300px', '100%'],
        offset: 'rt', // 右上角
        anim: 'slideLeft', // 从右侧抽屉滑出
        shadeClose: true,
        scrollbar: false,
        move: false,
        success: function(layero, index, that){
            top.API.common().loadPage(href,function (response){
                callback && typeof callback =='function'?callback(response):'';
            })
        }
    });
}
// 初始化弹窗表单
function openForm(options,eleId,html){
    let id = notify.loading({position:'vcenter'});
    if (!options.type){
        laytpl(eleId ? document.getElementById(eleId).innerHTML : html).render(options.data || {}, function(str){
            options.content = options.btn !== -1 ? str.replaceAll("disabled",""):str;
            popupWin(options)
        });
    }else {
        popupWin(options)
    }


    //弹窗
    function popupWin(options){
        layer.open({
            type: options.type || 1,
            area: options.area, // 宽高
            title: options.title,
            resize:false,
            scrollbar:false,
            move: false,
            btn: options.btn === 1 ? ['保存', '重置', '关闭']:[],
            btnAlign: 'c',
            btn1:function (index, layero, that){
                if (options.save && typeof options.save === 'function'){
                    options.save(index,layero,that)
                }
                return false
            },
            btn2:function (index, layero, that){
                if (options.reset && typeof options.reset === 'function'){
                    options.reset(index,layero,that)
                }
                return false
            },
            btn3:function (index, layero, that){
                if (options.close && typeof options.close === 'function'){
                    options.close(index,layero,that)
                }
            },
            success:function (layero, index, that){
                form.render($(layero).find('.layui-form'));
                if (options.before && typeof options.before === 'function'){
                    options.before(index,layero,that,options.btn === 1?'':'disabled')
                }
                notify.close(id);
            },
            cancel:function (index, layero, that){
                if (options.cancel && typeof options.cancel === 'function'){
                    options.cancel(index,layero,that)
                }
            },
            content: options.content
        });
    }
}
//图片预览
function clickImgView(elem){
    if ($(elem).find('img').length<=0){
        return;
    }
    let src = $(elem).find('img').attr('src')
    let id = $(elem).attr('id')
    let alt = $(elem).attr('avatar')
    layer.photos({
        photos: {
            "title": "图片预览",
            "start": 0,
            "data": [
                {
                    "alt": alt,
                    "pid": id,
                    "src": src,
                }
            ]
        },
        footer: false // 是否显示底部栏 --- 2.8.16+
    });
}

// 打开询问框
function openConfirm(confirm,cancel,title){
    layer.confirm(title || '是否确认删除？', {icon: 3,title:'系统提示'}, (index)=>{
        if (confirm && typeof confirm == 'function'){
            confirm();
        }
        layer.close(index);
    },(index)=>{
        if (cancel && typeof cancel == 'function'){
            cancel();
        }
        layer.close(index);
    });
}

// 页面查询条件初始化
function searchFormInfo(){
    /*
    * 生成字典查询条件
    * 字典组件格式： div class="dict-module" type="select|radio|checkbox" dict-type="字典类型" name city filter
    * */
    // 渲染页面
    workdbFieldConvert(document.querySelectorAll('.search-criteria .dict-module'));

    // 判断条件个数，控制显示按钮
    if ($('.search-criteria').find('input').length > 4){
        $('.search-criteria button.layui-hide').removeClass("layui-hide")
    }else {
        $('.search-criteria button.layui-hide').remove()
    }

    // 初始化页面上所有可清除的输入框
    initClearableInputs();
    /*
        form.on('input-affix(clear)', function(data){
        console.log(data)
        var elem = data.elem; // 获取输入框 DOM 对象
        elem.value="";
        });
     */

    // 初始化页面上所有可清除的输入框
    function initClearableInputs() {
        // 获取所有class为'layui-input'的input元素
        var inputs = document.querySelectorAll('.search-criteria .layui-input');
        // 为每个input元素添加事件监听
        inputs.forEach(function(input) {
            // 获取对应的清除按钮，如果不存在，则创建一个
            var clearButton = input.nextElementSibling;
            if (!clearButton || !clearButton.classList.contains('layui-input-affix')) {

                // 创建清除按钮
                clearButton = document.createElement('div');
                clearButton.className = 'layui-input-affix layui-input-suffix layui-hide';
                clearButton.innerHTML = '<i class="layui-icon layui-icon-clear"></i>';
                // 将清除按钮插入到input元素之后
                input.parentNode.insertBefore(clearButton, input.nextSibling);
            }
            // 监听input事件
            input.addEventListener('input', function() {
                // 根据输入框的内容显示或隐藏清除按钮
                if (this.value.trim() !== '') {
                    clearButton.classList.remove('layui-hide');
                } else {
                    clearButton.classList.add('layui-hide');
                }
            });

            // 监听清除按钮的点击事件
            clearButton.addEventListener('click', function() {
                // 清空输入框
                input.value = '';
                // 隐藏清除按钮
                clearButton.classList.add('layui-hide');
            });
        });
    }
}
// 字典转换
function workdbFieldConvert(element,isEdit=''){
    var workdbField = element;
    workdbField.forEach(function(dictEle) {
        let type = $(dictEle).attr("type");
        let dictType = $(dictEle).attr("dict-type");

        var dictData = top.tools.dict().getDictByType(dictType);
        let data = {
            id:$(dictEle).attr("id"),
            name:$(dictEle).attr("name"),
            filter:$(dictEle).attr("filter"),
            verify:$(dictEle).attr("verify"),
            title:$(dictEle).attr("title"),
            city:$(dictEle).attr("city"),
            disabled:$(dictEle).attr("disabled"),
            isEdit:isEdit,
            data:dictData
        }

        switch (type){
            case "select":
                laytpl(components.select).render(data, function(str){
                    $(dictEle).parent().html(str);
                });
                break;
            case "radio":
                laytpl(components.radio).render(data, function(str){
                    $(dictEle).parent().html(str);
                });
                break;
            case "checkbox":
                laytpl(components.checkbox).render(data, function(str){
                    $(dictEle).parent().html(str);
                });
                break;
        }
    })
    formSelectRender();
}

//显示查询条件
function showInput(event){
    let queryH = $('fieldset').outerHeight();
    let tableH = $('.layui-table-main').outerHeight()
    // 检查当前图标类名并切换
    if ($(event).find(".layui-icon-down").length > 0) {
        // 如果当前是 layui-icon-down，则切换为 layui-icon-up
        $(event).find('.layui-icon').removeClass('layui-icon-down');
        $(event).find('.layui-icon').addClass('layui-icon-up');
        $('.search-criteria .hide-input').show();

        $('.layui-table-main').css("height",(tableH - ($('fieldset').outerHeight()-queryH))+"px")
    } else {
        // 如果当前是 layui-icon-up，则切换为 layui-icon-down
        $(event).find('.layui-icon').removeClass('layui-icon-up');
        $(event).find('.layui-icon').addClass('layui-icon-down');
        $('.search-criteria .hide-input').hide();
        $('.layui-table-main').css("height",(tableH + (queryH-$('fieldset').outerHeight()))+"px")
    }
}

// 转换表格返回数据
function dataToFormat(res) {
    let code = res.code == 200 ? 0 : 1;
    let msg = res.message;
    let count = res.data.total || 0;
    let data = res.data.records || res.data.rows || [];
    return {
        "code": code, // 解析接口状态
        "msg": msg, // 解析提示文本
        "count": count, // 解析数据长度
        "data": data // 解析数据列表
    };
}

// 转换表格返回数据
function dataToTreeFormat(res) {
    let code = res.code == 200 ? 0 : 1;
    let msg = res.message;
    let count = 0;
    let data = [];
    if (tableReturnFilter && typeof tableReturnFilter == 'function'){
        data = tableReturnFilter(res.data.records || res.data);
        count = data.length;
    }
    return {
        "code": code, // 解析接口状态
        "msg": msg, // 解析提示文本
        "count": count, // 解析数据长度
        "data": data // 解析数据列表
    };
}

//渲染select组件
function formSelectRender(id){
    if (id){
        form.render($('#'+id));
    }else {
        form.render($('.search-criteria'));
        // 获取所有class为'layui-input'的input元素
        //var selects = document.querySelectorAll('.search-criteria select');
        // 为每个input元素添加事件监听
        //selects.forEach(function(select) {
        //    var id = $(select).attr("id");
        //    form.render($('#'+id));
        //});
    }
}
//表格查询数据
function queryButton(tableId){
    // 搜索提交
    form.on('submit(table-search)', function(data){
        var field = data.field; // 获得表单字段
        if (!checkAnyPropertyHasValue(field)) {
            var where = table.getOptions(tableId).defaultWhere;
            field = {...where,...field}
        }
        // 执行搜索重载
        table.reload(tableId, {
            page: {
                curr: 1 // 重新从第 1 页开始
            },
            where: field // 搜索的字段
        });
        return false; // 阻止默认 form 跳转
    });
    function checkAnyPropertyHasValue(obj) {
        return Object.values(obj).some(value => value!== undefined && value!== null && value!== '');
    }
}
function formReset(){
    // 表单赋值
    $('#reset').on('click', function(){
        form.val('reset-val-filter', top.tools.form.getFindElementOnObj(".search-criteria",false));
    });
}

function initIcon(callback){
    icon.init({
        el: $('.icon-btn'),
        on: function (icon){
            callback(icon,$('.icon-btn'));
            dropdown.close('iconPick');
        }
    })
}

async function sleep(time){
    await new Promise(resolve => setTimeout(resolve, time));
}